package com.fcy.teamwork.business.newjob

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.fcy.teamwork.base.*
import com.fcy.teamwork.business.recommendstudent.RecommendStudentActivity
import com.fcy.teamwork.databinding.ActivityNewJobBinding
import com.fcy.teamwork.pojo.Job
import com.fcy.teamwork.pojo.ProjectInfo
import kotlinx.coroutines.launch

class NewJobActivity : BaseActivity<ActivityNewJobBinding>() {
    private val vm: NewJobVM by viewModels()
    private lateinit var projectInfo: ProjectInfo
    override fun initBinding(): ActivityNewJobBinding =
        ActivityNewJobBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        parseArgs()
        binding.actionBar.apply {
            tvTitle.text = "创建岗位"
            ibFinish.visibility = View.VISIBLE
            ibFinish.setOnClickListener {
                if (binding.etJob.text.isNotBlank() && binding.etSkill.text.isNotBlank()) {
                    lifecycleScope.launch {
                        val job = Job().apply {
                            projectId = projectInfo.groupId
                            name = binding.etJob.text.toString()
                            requireSkills =
                                binding.etSkill.text.split(" ")
                                    .foldRightIndexed("") { index, it, acc ->
                                        if (index == 0) it
                                        else "$it,$acc"
                                    }
                        }
                        val res = vm.submitJob(job)
                        if (res.data.id != null) {
                            Intent(
                                this@NewJobActivity,
                                RecommendStudentActivity::class.java
                            ).apply {
                                putExtra("job", res.data.toJson())
                                startActivity(this)
                            }
                            finish()
                        } else {
                            toast(res.message)
                        }
                    }
                } else {
                    toast("请填写完整，再提交信息")
                }
            }
        }
    }

    private fun parseArgs() {
        projectInfo =
            intent.getStringExtra("project")?.fromJson()
                ?: throw IllegalArgumentException("未传入指定的projectInfo")
    }
}